package com.softme.trade.config;

import static net.sf.trugger.scan.ClassScan.findClasses;

import java.util.Properties;
import java.util.Set;

import javax.persistence.Entity;

import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;

public class SessionFactoryImpl extends AnnotationSessionFactoryBean
{
	public SessionFactoryImpl()
	{
		this.setDataSourceProperties();
		this.setHibernateProperties();
		this.setEntityClass();
	}

	private void setDataSourceProperties()
	{
		DriverManagerDataSource dataSource = new DriverManagerDataSource();

		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql://localhost/softme_trade");
		dataSource.setUsername("root");
		dataSource.setPassword("root");

		this.setDataSource(dataSource);
	}

	private void setHibernateProperties()
	{
		Properties hibernateProp = new Properties();

		//configurações do hibernate
		hibernateProp.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");
		hibernateProp.setProperty("hibernate.bytecode.use_reflection_optimizer", "true");
		hibernateProp.setProperty("hibernate.archive.autodetection", "class");
		hibernateProp.setProperty("hibernate.max_fetch_depth", "0");
		hibernateProp.setProperty("hibernate.connection.pool_size", "3");
		hibernateProp.setProperty("hibernate.hbm2ddl.auto", "update");
		hibernateProp.setProperty("hibernate.tool.hbm2ddl", "create");
		hibernateProp.setProperty("hibernate.show_sql", "true");
		hibernateProp.setProperty("hibernate.bytecode.provider", "cglib");
		hibernateProp.setProperty("hibernate.cache.provider_class",
				"org.hibernate.cache.NoCacheProvider");
		hibernateProp.setProperty("hibernate.cache.use_query_cache", "false");
		hibernateProp.setProperty("hibernate.cache.use_second_level_cache", "false");
		hibernateProp.setProperty("hibernate.query.jpaql_strict_compliance", "false");

		// Configurações do C3P0
		hibernateProp.setProperty("hibernate.connection.provider_class",
				"org.hibernate.connection.C3P0ConnectionProvider");
		hibernateProp.setProperty("hibernate.c3p0.acquire_increment", "1");
		hibernateProp.setProperty("hibernate.c3p0.idle_test_period", "100");//segundos
		hibernateProp.setProperty("hibernate.c3p0.max_size", "12");
		hibernateProp.setProperty("hibernate.c3p0.max_statements", "0");
		hibernateProp.setProperty("hibernate.c3p0.min_size", "4");
		hibernateProp.setProperty("hibernate.c3p0.timeout", "0");//segundos

		this.setHibernateProperties(hibernateProp);
	}

	private void setEntityClass()
	{
		//verifica quais classes possuem @entity
		Set<Class> classesPersistiveis = findClasses().recursively().annotatedWith(Entity.class)
				.in("com.softme.trade.model");

		this.setAnnotatedClasses(classesPersistiveis.toArray(new Class[classesPersistiveis.size()]));

	}
}
